package com.hxht.cmp.shiro;

import com.hxht.cmp.common.Constants;
import com.hxht.cmp.entity.User;
import com.hxht.cmp.entity.UserRole;
import com.hxht.cmp.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author alice on 2017/7/03 0001.
 * @version 1.0
 * @since 1.0
 */
public class CustomRealm extends AuthorizingRealm {
    private final Logger logger = LoggerFactory.getLogger(CustomRealm.class);
    @Resource
    private UserService userService;

    /**
     * 授权查询回调函数
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Session session = SecurityUtils.getSubject().getSession();
        User user = (User) session.getAttribute("user");
        if (null != user) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            List<UserRole> userRoleList = userService.getUserRole(userRole);
            session.setAttribute("roles", userRoleList);
            if (null != userRoleList && userRoleList.size() > 0) {
                for (UserRole r : userRoleList) {
                    info.addRole(r.getRoleName());
                }
            }
            return info;
        } else {
            SecurityUtils.getSubject().logout();
        }
        return null;
    }

    /**
     * 获取认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = new User();
        user.setUsername(token.getUsername());
        if (!"super".equalsIgnoreCase(token.getUsername())) {
            user.setCourtUid(Constants.CENTRAL_COURT.getUid());
        }
        user = userService.selectOne(user);
        if (null != user) {
            if (user.getAccountLocked() || user.getAccountExpired()) {
                throw new LockedAccountException();
            }
            Session session = SecurityUtils.getSubject().getSession();
            setSession(session,user);
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), user.getUsername());
        } else {
            throw new UnknownAccountException();//没找到帐号
        }
    }

    private void setSession(Session session,User user) {
        if ("super".equals(user.getUsername())) {
            user.setCourtUid(Constants.CENTRAL_COURT.getUid());
        }
        session.setAttribute("user", user);
        session.setAttribute("courtUid", user.getCourtUid());
    }
}
